<?php

class Controller_Admin_Account extends Controller
{
    public function __construct()
    {
        $aUser = getCurrentUser();
		if (!isset($aUser['utype']) || $aUser['utype'] != 'admin')
		{
		    Controller_Error::forbidden();
		}
    }
    
	public function index()
	{
	    if (isset($this->params[0]))
	    {
	        switch ($this->params[0])
	        {
	            case 'delete':
	                $id = isset($this->params[1]) ? intval($this->params[1]) : 0;
	                $account = new Model_Account($id);
	                $account->delete();
	                Redirect('/admin/account');
	            break;
	        }
	    }
	    $account = new Model_Account();
	    $aAccounts = $account->find();
		$this->view->add(array(
		    'aAccounts' => $aAccounts,
		));
		return $this->view->render('admin/account/list.tpl');
	}
	
	public function edit()
	{
	    $id = isset($this->params[0]) ? intval($this->params[0]) : 0;
	    $account = new Model_Account($id);
        $aData = $account->values;
	    $errors = array();
	    if (Request::isPost())
	    {
	        $aData = Request::getPost();
    		$validator = new Validator();
    		$validator->add(new Rule_NotEmpty('login', 'Введите логин'));
    		$validator->add(new Rule_NotEmpty('password', 'Введите пароль'));
    		$validator->add(new Rule_NotEmpty('name', 'Введите имя'));
    		$validator->add(new Rule_NotEmpty('utype', 'Выберите тип'));
    		if ($validator->validate($aData))
    		{
    		    if (Service_Account::loginIsExists($aData['login'], $id))
    		    {
    		        $errors['duplicate'] = 'Пользователь с таким логином уже существует';
    		    }
    		    else
    		    {
    		        if ($id)
    		        {
    		            $account->save($aData);
    		        }
    		        else
    		        {
    		            $account->values = $aData;
        		        $account->save();
    		        }
    		        Redirect('/admin/account');
    		    }
    		}
    		else
    		{
    		    $errors = $validator->errors;
    		}
	    }
	    
	    $aUserTypes = array(
	       'client'  => 'Клиент',
	       'manager' => 'Менеджер',
	       'admin'   => 'Администратор',
	       );
		$this->view->add(array(
		    'id'         => $id,
		    'aData'      => $aData,
		    'aUserTypes' => $aUserTypes,
		    'errors'     => $errors,
		));
		return $this->view->render('admin/account/edit.tpl');
	}
	

}